package com.jf.car.controller;

import com.alibaba.fastjson.JSON;
import com.jf.car.bean.Category;
import com.jf.car.service.CategoryService;
import com.jf.car.service.impl.CategoryServiceImpl;
import com.jf.car.util.MyUtils;
import com.jf.car.util.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/category")
public class CategoryServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        CategoryService categoryService = new CategoryServiceImpl();
        Category category = new Category();
        category.setId(MyUtils.string2Int(request.getParameter("id")));
        category.setName(request.getParameter("name"));
        category.setProfile(request.getParameter("profile"));
        category.setStatus(MyUtils.string2Int(request.getParameter("status")));
        if(MyUtils.isStringEmpty(param)){
            request.getRequestDispatcher("/WEB-INF/pages/admin/category/category-list.jsp").forward(request,response);
        }
        if("list".equals(param)){
            int page = MyUtils.string2Int(request.getParameter("page"),1);
            int limit = MyUtils.string2Int(request.getParameter("limit"),5);
            PageInfo pageInfo =  new PageInfo(page,limit);
            response.getWriter().println(JSON.toJSON(categoryService.getPage(pageInfo,category)));
        }
        if("edit".equals(param)){
            request.getRequestDispatcher("/WEB-INF/pages/admin/category/category-edit.jsp").forward(request,response);
        }
        if("select".equals(param)){
            response.getWriter().println(JSON.toJSON(categoryService.getSelect()));
        }
        if("info".equals(param)){
            response.getWriter().println(JSON.toJSON(categoryService.info(category.getId())));
        }
        if("update".equals(param)){
            response.getWriter().println(JSON.toJSON(categoryService.saveOrUpdate(category)));
        }
        if("delete".equals(param)){
            response.getWriter().println(JSON.toJSON(categoryService.delete(category.getId())));
        }
    }
}
